package greaderbook.frontend;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;

import greaderbook.backend.AuthenticationRequest;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Class for listening button clicks in AuthenticationView.
 * 
 * @author Jia Cherng Ho
 * 
 */
public class AuthSubmitListener implements OnClickListener {
	private AuthenticationRequest request;
	private Activity view;
	private EditText userText;
	private EditText passText;
	private TextView resultLbl;

	/**
	 * AuthSubmitListener contructor.
	 * 
	 * @param v
	 * 			  AuthenticationView activity
	 * @param utxt
	 *            username edit text field in AuthenticationView
	 * @param ptxt
	 *            password edit text field in AuthenticationView
	 * @param res
	 *            text view in AuthenticationView
	 */
	public AuthSubmitListener(Activity v, EditText utxt, EditText ptxt, TextView res) {
		view = v;
		userText = utxt;
		passText = ptxt;
		resultLbl = res;
		request = new AuthenticationRequest();
	}

	/**
	 * Retrieve SID with the username and password given in the text fields when
	 * the submit button in AuthenticationView is clicked.
	 * 
	 * @param v
	 *            the submit button in AuthenticationView
	 * @see AuthenticationView.java
	 */
	public void onClick(View v) {
		try {
			String sid = request.getSID(userText.getText().toString(),
					passText.getText().toString());
			Intent i = new Intent();
			if (sid != null) {
				i.putExtra("user", userText.getText().toString());
				i.putExtra("pass", passText.getText().toString());
				i.putExtra("sid", sid);
				view.setResult(Activity.RESULT_OK, i);
				view.finish();
			} else {
				resultLbl.setText("Incorrect username and/or password");
				view.setResult(Activity.RESULT_CANCELED);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
